import TimeModule from "./TimeModule";

const {ccclass, property} = cc._decorator;

@ccclass
export default class LogModule {
    private timeModule: TimeModule = null;
    private _logText: string = '';
    private _logPath: string = '';
    private _filePath: string = '';
    private _bindLabel: cc.Label[] = []; 

    public static module: LogModule = new LogModule();

    init () {
        this.timeModule = new TimeModule();
        let logDirPath = jsb.fileUtils.getWritablePath() + 'log/';
        if (jsb.fileUtils.isDirectoryExist(logDirPath) == false) {
            jsb.fileUtils.createDirectory(logDirPath);
        }
        this._logPath = logDirPath;
        this._filePath = logDirPath + `log_${this.timeModule.strToday()}.txt`;
        if (jsb.fileUtils.isFileExist(this._filePath)) {
            this._logText = jsb.fileUtils.getStringFromFile(this._filePath);
        }
    }

    static pushBindLabel (label) {
        LogModule.module._bindLabel.push(label);
    }

    static popBindLabel () {
        LogModule.module._bindLabel.pop();
        LogModule.log('关闭界面');
    }

    _logString (strLog) {
		this._logText += strLog;
        this._logText += '\n';
        this._checkLogFile();
        if (this._bindLabel.length > 0) {
            let label = this._bindLabel[this._bindLabel.length - 1];
            if (cc.isValid(label.node)) {
                label.string = strLog;
            }
        }
        console.log(strLog);
    }
    
    _checkLogFile () {
        let filePath = this._logPath + 'log_' + this.timeModule.strToday() +'.txt';
        if (filePath != this._filePath) {
            jsb.fileUtils.writeStringToFile(this._logText, this._filePath);
            this._filePath = filePath;
            this._logText = '';
        }
    }

    static log (str: string) {
        let strLog = LogModule.module.timeModule.formatTimeMs() + ':';
		strLog += str;
        LogModule.module._logString(strLog);
    }

    static logData (tag, obj) {
        let strLog = LogModule.module.timeModule.formatTimeMs() + ':';
        strLog += tag + '\n';
        if (obj) {
            strLog += JSON.stringify(obj);
        }
        LogModule.module._logString(strLog);
    }

    save () {
        jsb.fileUtils.writeStringToFile(this._logText, this._filePath);
        let filePath = this._logPath + 'log' + this.timeModule.strToday() +'.txt';
        if (this._filePath != filePath) {
            this._filePath = filePath;
            this._logText = '';
        }
    }

}
